package com.example.demo.controller;

import com.example.demo.common.R;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public R<List<User>> list() {
        return R.success(userService.list());
    }

    @GetMapping("/{id}")
    public R<User> getById(@PathVariable Long id) {
        return R.success(userService.getById(id));
    }

    @PostMapping
    public R<Boolean> save(@RequestBody User user) {
        return R.success(userService.save(user));
    }

    @PutMapping("/{id}")
    public R<Boolean> update(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        return R.success(userService.updateById(user));
    }

    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Long id) {
        return R.success(userService.removeById(id));
    }

    @GetMapping("/count")
    public R<Long> countByAgeRange(
            @RequestParam(required = false) Integer minAge,
            @RequestParam(required = false) Integer maxAge) {
        return R.success(userService.countUsersByAgeRange(minAge, maxAge));
    }
} 